"""GitLab API服务"""
import requests
from typing import List, Dict, Any
from config.gitlab_config import GITLAB_CONFIG
from utils.logger import sync_logger

class GitLabService:
    def __init__(self):
        self.headers = {'PRIVATE-TOKEN': GITLAB_CONFIG['token']}
        self.base_url = f"{GITLAB_CONFIG['url']}/api/{GITLAB_CONFIG['api_version']}"

    def get_all_projects(self) -> List[Dict[str, Any]]:
        """获取所有项目列表"""
        with sync_logger.start_timer("获取项目列表"):
            projects = []
            page = 1
            
            while True:
                url = f"{self.base_url}/projects"
                params = {'page': page, 'per_page': GITLAB_CONFIG['per_page']}
                
                try:
                    response = requests.get(url, headers=self.headers, params=params, timeout=GITLAB_CONFIG['timeout'])
                    if response.status_code == 200:
                        page_projects = response.json()
                        if not page_projects:
                            break
                        projects.extend(page_projects)
                        page += 1
                    else:
                        sync_logger.log_error(f"获取项目列表失败: {response.status_code}")
                        break
                except Exception as e:
                    sync_logger.log_error(f"获取项目列表时发生错误: {e}")
                    break
            
            sync_logger.log_info(f"共获取到 {len(projects)} 个项目")
            return projects

    def get_project_commits(self, project_id: int) -> List[Dict[str, Any]]:
        """获取指定项目的所有提交"""
        with sync_logger.start_timer(f"获取项目 {project_id} 的提交列表"):
            commits = []
            page = 1
            
            while True:
                url = f"{self.base_url}/projects/{project_id}/repository/commits"
                params = {'page': page, 'per_page': GITLAB_CONFIG['per_page']}
                
                try:
                    response = requests.get(url, headers=self.headers, params=params, timeout=GITLAB_CONFIG['timeout'])
                    if response.status_code == 200:
                        page_commits = response.json()
                        if not page_commits:
                            break
                        commits.extend(page_commits)
                        page += 1
                    else:
                        sync_logger.log_error(f"获取项目 {project_id} 的提交列表失败: {response.status_code}")
                        break
                except Exception as e:
                    sync_logger.log_error(f"获取项目 {project_id} 的提交列表时发生错误: {e}")
                    break
            
            sync_logger.log_info(f"项目 {project_id} 共获取到 {len(commits)} 个提交")
            return commits

    def get_all_members(self) -> List[Dict[str, Any]]:
        """获取所有成员信息"""
        with sync_logger.start_timer("获取成员列表"):
            members = []
            page = 1
            
            while True:
                url = f"{self.base_url}/users"
                params = {'page': page, 'per_page': GITLAB_CONFIG['per_page']}
                
                try:
                    response = requests.get(url, headers=self.headers, params=params, timeout=GITLAB_CONFIG['timeout'])
                    if response.status_code == 200:
                        page_members = response.json()
                        if not page_members:
                            break
                        members.extend(page_members)
                        page += 1
                    else:
                        sync_logger.log_error(f"获取成员列表失败: {response.status_code}")
                        break
                except Exception as e:
                    sync_logger.log_error(f"获取成员列表时发生错误: {e}")
                    break
            
            sync_logger.log_info(f"共获取到 {len(members)} 个成员")
            return members

    def get_project_members(self, project_id: int) -> List[Dict[str, Any]]:
        """获取指定项目的成员信息"""
        with sync_logger.start_timer(f"获取项目 {project_id} 的成员列表"):
            members = []
            page = 1
            
            while True:
                url = f"{self.base_url}/projects/{project_id}/members"
                params = {'page': page, 'per_page': GITLAB_CONFIG['per_page']}
                
                try:
                    response = requests.get(url, headers=self.headers, params=params, timeout=GITLAB_CONFIG['timeout'])
                    if response.status_code == 200:
                        page_members = response.json()
                        if not page_members:
                            break
                        members.extend(page_members)
                        page += 1
                    else:
                        sync_logger.log_error(f"获取项目 {project_id} 的成员列表失败: {response.status_code}")
                        break
                except Exception as e:
                    sync_logger.log_error(f"获取项目 {project_id} 的成员列表时发生错误: {e}")
                    break
            
            sync_logger.log_info(f"项目 {project_id} 共获取到 {len(members)} 个成员")
            return members 